<?php

class sbOrders {

    public function getMyOrders($id, $order_id, $sort, $date, $page) {
        $offset = ($page * sbValues::HOTELS_IN_ADMIN_PAGE) - sbValues::HOTELS_IN_ADMIN_PAGE;
        switch ($sort) {
            case sbValues::ORDER_SORT_TODAY:
                return $this->searchByOrderToday($id, $offset);
            case sbValues::ORDER_SORT_MONTH:
                return $this->searchByOrderLastMonth($id, $offset);
            case sbValues::ORDER_SORT_DATE:
                return $this->searchByOrderDate($id, $date, $offset);
            case sbValues::ORDER_SORT_ID:
                return $this->searchByOrderId($order_id, $id);
        }
    }

    private function searchByOrderLastMonth($id, $offset) {
        if (is_null($id)) {
            return null;
        }

        $last_mount = date('Y-m-d H:i:s', strtotime('-1 month'));
        $orders = Doctrine_Query::create()->
                select('*')->
                from('tblOrders')->
                where('user_id=? AND create_by>?', array($id, $last_mount))->
                offset($offset)->
                limit(sbValues::HOTELS_IN_ADMIN_PAGE)->
                execute();

        if ($orders) {
            $arrOrders = $orders->toArray();
            return $this->insertHotelData($arrOrders);
        } else {
            return null;
        }
    }

    private function searchByOrderDate($id, $date, $offset) {
        if (is_null($id) || is_null($date)) {
            return null;
        }

        $orders = Doctrine_Query::create()->
                select('*')->
                from('tblOrders')->
                where('user_id=? AND create_by BETWEEN ? AND ?', array($id, $date['from_date'], $date['to_date']))->
                offset($offset)->
                limit(sbValues::HOTELS_IN_ADMIN_PAGE)->
                execute();

        if ($orders) {
            $arrOrders = $orders->toArray();
            return $this->insertHotelData($arrOrders);
        } else {
            return null;
        }
    }

    private function searchByOrderToday($id, $offset) {
        if (is_null($id)) {
            return null;
        }

        $orders = Doctrine_Query::create()->
                select('*')->
                from('tblOrders')->
                where('user_id=? and create_by>?', array($id, sbValues::getDateToDB() . ' 00:00:00'))->
                limit(sbValues::HOTELS_IN_ADMIN_PAGE)->
                offset($offset)->
                execute();

        if ($orders) {
            $arrOrders = $orders->toArray();
            return $this->insertHotelData($arrOrders);
        } else {
            return null;
        }
    }

    private function searchByOrderId($order_id, $id) {
        $order = tblOrdersTable::getInstance()->findByDql('id=? and user_id=?', array($order_id, $id))->getFirst();
        if ($order) {
            $arrOrder = array();
            $temp = $order->toArray();
            array_push($arrOrder, $temp);
            return $this->insertHotelData($arrOrder);
        } else {
            return null;
        }
    }

    private function insertHotelData($orders) {
        $arrOrders = array();
        foreach ($orders as $o) {
            $objHotel = tblHotelTable::getInstance()->findByDql('id=?', $o['hotel_id'])->getFirst();
            $arrHotel = $objHotel->toArray();
            $roomsInfo = $this->insertRoomsData($o['hotel_id'], $o['rooms_id']);
            $o['Hotel'] = $arrHotel;
            $o['Rooms'] = $roomsInfo;
            array_push($arrOrders, $o);
        }
        return $arrOrders;
    }

    private function insertRoomsData($hotelId, $roomsId) {
        if (is_null($roomsId) || is_null($hotelId)) {
            return null;
        }

        $parseRooms = explode(';', $roomsId);
        $roomsInfo = array();
        for ($i = 0; $i < count($parseRooms) - 1; $i++) {
            $temp = tblRoomsTable::getInstance()->findByDql('id=? and hotel_id=?', array($parseRooms[$i], $hotelId))->getFirst();
            $room = $temp->toArray();
            array_push($roomsInfo, $room);
        }
        return $roomsInfo;
    }

    public function cancellationOrder($order_id) {
        $order = tblOrdersTable::getInstance()->findByDql('id=?', $order_id)->getFirst();
        if ($order) {
            if ($order->getStatus()) {
                $hotel = tblHotelTable::getInstance()->findByDql('id=?', $order->getHotelId())->getFirst();

                switch ($hotel->getProviderId()) {
                    case sbValues::PROVIDER_GOC:
                        return $this->cancellationOrderGoc($order, $hotel);
                    case sbValues::PROVIDER_ISR:
                        return $this->cancellationOrderIsr($order, $hotel);
                    case sbValues::PROVIDER_DAN:
                }
            } else {
                return 'this order already cancel';
            }
        } else {
            return 'this order id not found';
        }
    }

    public function cancellationOrderIsr($order, $hotel) {
        $order->setStatus(sbValues::ORDER_STATUS_PROCCESS);
        $order->setCancellationDate(sbValues::getDateToDB());
        $order->save();
        return true;
    }

    public function cancellationOrderGoc($order, $hotel) {
        $hotelProviderId = $hotel->getProviderCode();
        $orderProviderId = $order->getProviderId();
        $parseRooms = explode(';', $order->getRoomsId());
        $goc = new sbGoc();
        $request = $goc->cancelBooking($client['cause'], $orderProviderId, (count($parseRooms) - 1), $hotelProviderId);
        $response = $goc->parseCancelBooking($request);

        $provider_order = $order->getProviderOrder();
        $order->setProviderOrder($provider_order . ' [Cancellation] ' . $response['status'] . ' ' . $response['cancellation']);
        if ($response['code'] == 0 && $response['status'] == 'Success') {
            $order->setStatus(sbValues::ORDER_STATUS_CANCEL);
        } else {
            $order->setStatus(sbValues::ORDER_STATUS_PROCCESS);
        }
        $order->setCancellationDate(sbValues::getDateToDB());
        $order->save();

        return $response;
    }
    
    public function sendMailCancellationToAgent($order_id) {
        $order = tblOrdersTable::getInstance()->findByDql('id=?', $order_id)->getFirst();
        $user = tblUsersTable::getInstance()->findByDql('id=? AND permissions=?', array($order->getUserId(), sbValues::PERMISSIONS_AGENT))->getFirst();
        $subject = 'Cancellation order '. $order->getId();
        $message = '<div><h3>Клиент желает отменить заказ - номер '.$order->getId().'</h3></div>'.
                '<div>Данные по заказу можно посмотреть здесь: </div>'.
                '<div>'.sbValues::URL_SERVER.'vaucher/order/'.$order->getId().'</div>';
        if ($user) {
            $to = array($user->getEmail(), sbValues::MAIL_SUPPORT_TROLI);
        } else {
            $to = array(sbValues::MAIL_SUPPORT_TROLI);
        }
        foreach ($to as $t) {
            sbValues::createNewEmailToAgent($t, $subject, $message);
        }
    }

}
